home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10929 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: hal.COM!spike
  2. From: spike@hal.com (Spike White)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: A template question...
  5. Date: 11 Mar 1996 20:25:13 GMT
  6. Organization: HAL Computer Systems, Inc.
  7. Message-ID: <4i2279$hes@news.hal.com>
  8. References: <4hkjn5$mp1@wapping.ecs.soton.ac.uk>
  9. NNTP-Posting-Host: zarathustra.hal.com
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Tony Lofthouse (tl93@ecs.soton.ac.uk) wrote:
  13. : I want a generic function to perform a sort on an array, so I do the 
  14. : following:
  15.  
  16. : template <class T>
  17. : void mysort(const T* anArray, unsigned arraysize) {
  18. :     // implementation   stuff
  19. : }
  20.  
  21. : o.k. fine. But I also want to pass a pointer to a predicate function which
  22. : does the comparasion of elements in the array. It seems to me that this 
  23. : predicate function needs to be a template function as well:
  24.  
  25. : template <class T>
  26. : unsigned greaterthan(const T& x, const T& y) {
  27. :     return x > y;
  28. : }
  29.  
  30. : so my implementation of mysort is:
  31.  
  32.  
  33. : template<class T>
  34. : void mysort(const  T* anArray, unsigned arraylen,
  35. :             unsigned (*predicate) (const T&, constT&)) {
  36.  
  37. :     // sort stuff
  38. :     if(predicate( el1, el2 ) {
  39. :     
  40. :     // ----    
  41. :     
  42. :     }
  43. :     //more sort stuff
  44.  
  45. : }
  46.  
  47. : Unfortunately when I do:
  48.  
  49. : extern int* anArray;
  50. : extern unsigned anArrayLength;
  51.  
  52. : mysort(anArray, anArrayLength, &greaterthan);
  53.  
  54. I'm a bit of a novice, but...it all looks good to me, except your last
  55. line should be:
  56.  
  57.    mysort(anArray, anArrayLength, greaterthan);
  58.  
  59. --
  60. Spike White          | spike@hal.com               | Biker Nerds
  61. HaL Software Systems | '87 BMW K75S, DoD #1347     |  From  HaL
  62. Austin, TX           |  http://www.halsoft.com/users/spike/index.html 
  63. Disclaimer:  HaL, want me to speak for you?  No, Dave... 
  64.